package com.ouc.pampas.controller;
import com.google.common.base.Strings;
import com.ouc.openplatform.pampas.UserUtil;
import com.ouc.pampas.Splitters;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Entrance {
	@Autowired
	private ViewRender viewRender;
	@Autowired
	private AssetsHandler assetsHandler;
	@Autowired
	private MappingHandler mappingHandler;

	//@RequestHeader 注解，可以把Request请求header部分的值绑定到方法的参数上。
	@RequestMapping
	public void doRequest(@RequestHeader("Host") String host, HttpServletRequest request, HttpServletResponse response,
			Map<String, Object> context) {
		String domain = (String) Splitters.COLON.splitToList(host).get(0);
		String path = request.getRequestURI().substring(request.getContextPath().length() + 1);
		if (Strings.isNullOrEmpty(path)) {
			path = "index";
		}
		context = prepareContext(request, context);
		boolean isAssets = this.assetsHandler.handle(path, response);
		if (isAssets) {
			return;
		}
		boolean hasMapping = this.mappingHandler.handle(path, request, response, context);
		if (hasMapping) {
			return;
		}
		this.viewRender.view(domain, path, response, context);
	}

	private Map<String, Object> prepareContext(HttpServletRequest request, Map<String, Object> context) {
		if (request != null) {
			for (Object name : request.getParameterMap().keySet()) {
				context.put((String) name, request.getParameter((String) name));
			}
		}
		context.put("_USER_", UserUtil.getCurrentUser());
		return context;
	}
}
